﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Windstamp.Utility.BookDownload.Common;
using Windstamp.Utility.BookDownload.Entity;

namespace Windstamp.Utility.BookDownload.Core {
    class ImageDownload {
        /// <summary>
        /// 停止
        /// </summary>
        public static bool Stop = false;

        /// <summary>
        /// 下载正文指定图片
        /// </summary>
        /// <param name="beginPageNum">起始页</param>
        /// <param name="folder">存放文件夹</param>
        /// <param name="info">主页面实体</param>
        /// <returns>运行状态</returns>
        public static int GetMainImage(int beginPageNum, string folder, MainPageInfo info) {
            return GetImage(beginPageNum, folder, info, PageType.Text);
        }
        /// <summary>
        /// 下载指定图片
        /// </summary>
        /// <param name="beginPageNum">起始页</param>
        /// <param name="folder">存放文件夹</param>
        /// <param name="info">主页面实体</param>
        /// <param name="type">下载的页面类型</param>
        /// <returns>运行状态</returns>
        public static int GetImage(int beginPageNum, string folder, MainPageInfo info, PageType type) {
            string[] imgTrueUrls = new string[info.ImgOriginalUrls.Length];
            bool finishied = false;
            int count403 = 0;
            for(int i = 0; i < info.ImgOriginalUrls.Length; i++) {
                if(Stop) {
                    Stop = false;
                    // 返回 3 表示被请求停止
                    return 3;
                }
                string imgFileName = "";
                string url = "", imgName = "";
                switch(type) {
                    case PageType.Cover:
                        imgName = string.Format("{0:cov000}", i + 1);
                        imgFileName = "!1" + imgName + (i == 0 ? "封面" : "封底") + ".png";
                        url = info.ImgOriginalUrlTemp.Replace("{Temp:0}", imgName);
                        break;
                    case PageType.Title:
                        imgName = string.Format("{0:bok000}", i + 1);
                        imgFileName = "!2" + imgName + "书名页.png";
                        url = info.ImgOriginalUrlTemp.Replace("{Temp:0}", imgName);
                        break;
                    case PageType.Copyright:
                        imgName = string.Format("{0:leg000}", i + 1);
                        imgFileName = "!3" + imgName + "版权页.png";
                        url = info.ImgOriginalUrlTemp.Replace("{Temp:0}", imgName);
                        break;
                    case PageType.Preface:
                        imgName = string.Format("{0:fow000}", i + 1);
                        imgFileName = "!4" + imgName + "前言.png";
                        url = info.ImgOriginalUrlTemp.Replace("{Temp:0}", imgName);
                        break;
                    case PageType.Index:
                        imgName = string.Format("{0:!00000}", i + 1);
                        imgFileName = "!5" + imgName + "目录.png";
                        url = info.ImgOriginalUrlTemp.Replace("{Temp:0}", imgName);
                        break;
                    case PageType.Text:
                        imgFileName = string.Format("{0:000000}.png", beginPageNum + i);
                        url = info.ImgOriginalUrls[i];
                        break;
                }
                if(File.Exists(Path.Combine(folder, imgFileName))) {
                    continue;
                }
                if(i > 0) {
                    System.Threading.Thread.Sleep(TimeHelper.Inteval);
                }

                var request = UrlRequestHelper.BuildRequest(url, "utf-8");
                request.AllowAutoRedirect = false;
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(info.Cookies);
                try {
                    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                        string location = response.Headers.Get("Location");
                        if(location == null) {
                            // 返回 2 表示未获取到重定向 Url
                            return 2;
                        }
                        imgTrueUrls[i] = location;
                        // 以 antispiderShowVerify.ac 结尾的 Url 即需要输入验证码
                        if(imgTrueUrls[i].Trim().EndsWith("antispiderShowVerify.ac")) {
                            // 返回 1 表示需要输入验证码
                            return 1;
                        }

                        byte[] imgBytes = GetImageContent(imgTrueUrls[i]);

                        if(type != PageType.Text && imgBytes.Length < 800) {
                            // 该类附属页下载完成
                            return 0;
                        }

                        string dir = folder;
                        if(!Directory.Exists(dir)) {
                            Directory.CreateDirectory(dir);
                        }
                        File.WriteAllBytes(Path.Combine(dir, imgFileName), imgBytes);
                    }
                } catch(Exception ex) {
                    if(ex.Message.IndexOf("(403)") != -1) {
                        if(count403 <= 10) {
                            i--;
                            count403++;
                            System.Threading.Thread.Sleep(100);
                            continue;
                        } else {
                            // 出现 403 错误
                            return 403;
                        }
                    }
                    throw new Exception(ex.Message, ex);
                }
                count403 = 0;
                PromptHelper.Handlers["StatusStripMsg"](string.Format("[{0}] 完成", imgFileName), PromptType.Information);

                switch(type) {
                    case PageType.Cover:
                        if(i == 1)
                            finishied = true;
                        break;
                    case PageType.Title:
                        finishied = true;
                        break;
                    case PageType.Copyright:
                        finishied = true;
                        break;
                    case PageType.Preface:
                        //File.AppendAllText(@"D:\mm\Preface.txt", imgTrueUrls[i]);
                        if(i == 199)
                            finishied = true;
                        break;
                    case PageType.Index:
                        //File.AppendAllText(@"D:\mm\i.txt", imgTrueUrls[i]);
                        if(i == 499)
                            finishied = true;
                        break;
                }
                if(finishied) {
                    break;
                }
            }
            // 返回 0 表示正常退出
            return 0;
        }
        private static byte[] GetImageContent(string picName) {
            //string fileURL = GetImgUrlPrefix() + picName;
            string fileURL = picName;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileURL);
            request.AllowAutoRedirect = true;

            WebProxy proxy = new WebProxy();
            proxy.BypassProxyOnLocal = true;
            proxy.UseDefaultCredentials = true;

            request.Proxy = proxy;

            WebResponse response = request.GetResponse();

            using(Stream stream = response.GetResponseStream()) {
                using(MemoryStream ms = new MemoryStream()) {
                    Byte[] buffer = new Byte[1024];
                    int current = 0;
                    while((current = stream.Read(buffer, 0, buffer.Length)) != 0) {
                        ms.Write(buffer, 0, current);
                    }
                    return ms.ToArray();
                }
            }
        }
    }
}
